/**
 * Created by felix on 2017/2/25.
 */
import React from 'react';
import _ from 'lodash';
import TD from './td';
/*
 * data          整条item数据
 * cols          列设置
 *   title         列表头名称
 *   dataIndex     字段名称
 *   width         列宽度，单位px
 *   render        返回dom的方法，参数分别是dataIndex对应的data值，和data对象
 * index         tr的序号，表示第几行，用TBody传下来的
 * onPress       点击行的回调
 * */
function TR({ data, cols, index, onPress }) {
    const clickHandle = (e) => {
        e.preventDefault();
        if (typeof onPress === 'function') {
            onPress(index);
        }
    };
    const items = (data, cols, index) => _.map(cols, (col, i) => {
        const { dataIndex, width, render } = col;
        const record = data;
        const text = data[dataIndex];
        let d;
        if (typeof render === 'function') {
            d = render(text, record);
        } else {
            d = text;
        }
        return (
            <TD
                data={d}
                width={width}
                key={`td_${index}_${i}`}
            />
        );
    });
    return (
        <tr
            onClick={clickHandle}
        >
            {items(data, cols, index)}
        </tr>
    );
}

export default TR;
